const http = require("http");
const URL = require("url");
const querystring = require('querystring');
const { sqlite, database } = require('../JDBC');
const { println } = require("../Console");
const { ipcMain } = require('electron')

/**  本地监听端口   */


//当前是否已经开启
let isOpen = false;

let httpServer = null;

//存储过滤器
const filters = [

    //设置消息返回体为json
    function setJsonBody(request, response) {
        response.writeHead(200, {
            'Content-Type': 'application/json; charset=utf-8'
        });
    },
];

//存储监听器
const listeners = {};



//匹配监听器
const matchingListener = (uri) => {

}

//获取所有监听器副本
const getAllListeners = () => {
    const map = Object.keys(listeners);
    return map.map(e => JSON.stringify(e));
}

//获取所有过滤器副本
const getAllFilters = () => {
    const array = filters.map(f => f.toString());
    return array;
}

//默认404处理
let listener404 = (request, response) => {
    response.writeHead(200, {
        'Content-Type': 'application/xhtml+xml; charset=utf-8'
    });
    response.end(`<html><body>错误404,未找到路径</body></html>`);
}


//打开监听服务 默认是不开启的
const openListenServer = () => {
    if (isOpen) {
        return true;
    }

    sqlite.config.queryByName("server").then(result => {
        //查询到端口
        let port = 61200;
        if (result && result.value) {
            port = parseInt(result.value);
        }

        httpServer = http.createServer(function (request, response) {
            //依次执行过滤器
            filters.forEach(filter => {
                filter(request, response)
            })

            //匹配uri
            const uri = request.url;
            const listener = matchingListener(uri);
            if (listener) {
                listener(request, response);
            } else {
                listener404(request, response);
            }

            //返回响应
            response.end();
        })

        httpServer.listen(port);
        console.log(`已开启本地端口监听(${port})`)
        println(`已开启本地端口监听(${port}),如需更改端口,请在设置页面进行更改`);
    })

    return isOpen = true;;
}

//重启监听服务
const restartListenServer = () => {
    if (httpServer) {
        httpServer.closeAllConnections();
    }

    isOpen = false;
    openListenServer();
}

//添加一个过滤器
//分发url前对resq和resp进行处理
//@paran filter:fn(resq,resp) 处理函数
const addFilter = (filter) => {
    filters.push(filter);
}

//添加一个监听器
//对指定url进行拦截
//@param uri:string  拦截路径, *为通配符
//@paran listener:fn(resq,resp) 处理函数
const addListener = (uri, listener) => {
    listeners[uri] = listener;
}

const init = () => {
    ipcMain.on("open-http-server", function (event) {
        openListenServer();
    })

    ipcMain.on("restart-http-server", function (event) {
        openListenServer();
    })


    ipcMain.on("http-server-addfilter", (event, fn) => {
        filters.push(fn);
    })

    ipcMain.on("http-server-addlistener", (event, uri, fn) => {
        listeners[uri] = fn;
    })

    ipcMain.handle("http-server-getfilter", (event, fn) => {
        return getAllListeners();
    })

    ipcMain.handle("http-server-getlistener", (event, fn) => {
        return getAllListeners();
    })
}

init();

module.exports = {
    getAllListeners,
    getAllFilters,
    openListenServer,
    restartListenServer,
    addFilter,
    addListener,
}